﻿using Core.Enums;
using Core.Tools;
using System;
using System.Collections.Generic;
using System.Data.Common;

namespace Core.Reader
{
    public class OverrideSqlDataReader : IDataReader
    {
        private readonly DbDataReader InternalReader;
        private readonly RWTypes InternalObjectType;

        public OverrideSqlDataReader(DbDataReader Reader, RWTypes ObjectType = RWTypes.Table)
        {
            InternalReader = Reader;
            InternalObjectType = ObjectType;
        }

        public object this[string Name]
        {
            get
            {
                return InternalReader[Name];
            }
        }

        public object this[int Index]
        {
            get
            {
                return InternalReader[Index];
            }
        }

        public IEnumerable<string> Fields
        {
            get
            {
                return new CollectionEnumerable<string>((Index) =>
                {
                    return InternalReader.GetName(Index);

                }, InternalReader.FieldCount, true);
            }
        }

        public int Count
        {
            get
            {
                return InternalReader.FieldCount;
            }
        }

        public RWTypes ObjectType
        {
            get
            {
                return InternalObjectType;
            }
        }

        public void Dispose()
        {
            InternalReader.Close();
        }

        public bool Read()
        {
            return InternalReader.Read();
        }

        public bool TryGetValue(string Name, out object Value)
        {
            int Index;

            try
            {
                Index = InternalReader.GetOrdinal(Name);
            }
            catch (IndexOutOfRangeException)
            {
                Value = null;

                return false;
            }

            Value = InternalReader.GetValue(Index);

            return true;
        }
    }
}
